<?php
namespace app\framework\lib;
use Monolog\Level;
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Formatter\LineFormatter;
use Psr\Log\LogLevel;
use think\db\Connection;
class MonologHandler implements LoggerInterface
{
    /** @var Logger Monolog实例 */
    private $logger;

    /**
     * 初始化Monolog配置
     * @param string $logDir 日志存储目录
     */
    public function __construct()
    {
        // 创建Monolog实例（指定通道名）

        $config = Config::getInstance()->mysql;
        $this->logger = new Logger($config["channel"]);


        // 日志目录（默认：项目根目录/logs/orm/）
        $logDir = $config["log_dir"];
        $maxFiles =$config["max_files"];
        // 按天切割日志，保留30天
        $handler = new RotatingFileHandler(
            $logDir ,  // 日志文件路径
            $maxFiles,                   // 保留文件数量
            Level::Debug         // 最低日志级别
        );
        // 自定义日志格式（时间 + 级别 + 进程ID + 内容）
        $formatter = new LineFormatter(
            "[%datetime%] [%level_name%] [PID:%extra.pid%] %message%\n",
            'Y-m-d H:i:s'
        );
        $handler->setFormatter($formatter);

        // 添加进程ID标识（多进程环境下区分日志来源）
        $this->logger->pushProcessor(function ($record) {
            $record['extra']['pid'] = posix_getpid();
            return $record;
        });

        $this->logger->pushHandler($handler);

    }

    public function emergency(\Stringable|string $message, array $context = []): void
    {
        $this->logger->emergency($message, $context);
    }

    public function alert(\Stringable|string $message, array $context = []): void
    {
        $this->logger->alert($message, $context);
    }

    public function critical(\Stringable|string $message, array $context = []): void
    {
        $this->logger->critical($message, $context);
    }

    public function error(\Stringable|string $message, array $context = []): void
    {
        $this->logger->error($message, $context);
    }

    public function warning(\Stringable|string $message, array $context = []): void
    {
        $this->logger->warning($message, $context);
    }

    public function notice(\Stringable|string $message, array $context = []): void
    {
        $this->logger->notice($message, $context);
    }

    public function info(\Stringable|string $message, array $context = []): void
    {
        $this->logger->info($message, $context);
    }

    public function debug(\Stringable|string $message, array $context = []): void
    {
        $this->logger->debug($message, $context);
    }

    public function log($level, \Stringable|string $message, array $context = []): void
    {
        if ($level=="sql") {
            $level ="info";
        }
        $this->logger->log($level, $message, $context);
    }

}
